import { computed, ref } from "vue";
import { DataGridColumn, DataGridProps } from "../data-grid.props";
import { UseDataRow, UseGroupRow, UseVisualDataCell, VisualData, VisualDataCell, VisualDataType } from "./types";

export function useVisualGroupRow(
    props: DataGridProps,
    useVisualDataCell: UseVisualDataCell,
    useVisualDataRowComposition: UseDataRow
): UseGroupRow {

    const identifyField = ref(props.idField);

    const summaryOptions = ref(props.summary);

    const { createCellByField } = useVisualDataCell;
    const { createEmptyRow } = useVisualDataRowComposition;

    const groupSummaryFields = computed(() => {
        const options = summaryOptions.value;
        return options?.groupFields || [];
    });

    const shouldShowColumnSummary = computed(() => {
        const options = summaryOptions.value;
        return options && options.enable && options.groupFields && options.groupFields.length > 0;
    });

    function renderSummeryInGroupRow(currentRow: VisualData, groupField: string, dataItem: any, columns: DataGridColumn[]) {
        if (shouldShowColumnSummary.value) {
            const groupFieldCell = currentRow.data[groupField];
            let groupCellColumnSpanCount = groupFieldCell.colSpan;
            const groupSummaryMap = groupSummaryFields.value.reduce((mapResult: Map<string, boolean>, groupField) => {
                mapResult.set(groupField, true);
                return mapResult;
            }, new Map<string, boolean>());
            columns.reduce((groupRow: VisualData, column: DataGridColumn, columnIndex: number) => {
                if (groupSummaryMap.has(column.field)) {
                    const currentCell: VisualDataCell = createCellByField(column.field, columnIndex, dataItem, currentRow);
                    currentRow.data[column.field] = currentCell;
                    if (groupCellColumnSpanCount - 1 > columnIndex) {
                        groupCellColumnSpanCount = columnIndex;
                    }
                }
                return groupRow;
            }, currentRow);
            groupFieldCell.colSpan = groupCellColumnSpanCount;
        }
    }

    function renderGroupRow(
        dataItem: any, preDataItem: any, preRow: VisualData,
        rowIndex: number, top: number, columns: DataGridColumn[]
    ): VisualData {
        const groupField = dataItem.__fv_data_grid_group_field__;
        const currentRow: VisualData = createEmptyRow(VisualDataType.group, rowIndex, dataItem, preDataItem, top);
        currentRow.data[identifyField.value] = createCellByField(identifyField.value, -1, dataItem, currentRow, 0);
        currentRow.data[groupField] = createCellByField(groupField, 1, dataItem, currentRow, columns.length);
        renderSummeryInGroupRow(currentRow, groupField, dataItem, columns);
        return currentRow;
    }

    return { renderGroupRow };
}
